<template>
	<div class="group-add maxW">
		<div class="crumbs-link">
			<span @click="back">我的圈组</span>
			<strong>
				<i>></i>
				新建圈组
			</strong>
		</div>
		<div class="group-add-cont">
			<el-form class="group-add-form" ref="form" :model="form" :rules="rules" label-width="100px">
				<el-form-item label="封面图片" prop="imageUrl2">
					<imgUpload v-on:picture="getImgPath"></imgUpload>
				</el-form-item>
				<el-form-item label="圈组名称" prop="name">
					<el-input class="group-name" v-model.trim="form.name" placeholder="最多可以输入20个字符" maxlength="20"></el-input>
				</el-form-item>
				<!-- 单级 -->
				<template v-if="isSchool">
					<el-form-item label="学段" prop="sectionId" class="g-item-inline">
						<el-select v-model="form.sectionId" @change="getGrade" placeholder="请选择学段">
							<el-option v-for="(item, index) in sectionData" :label="item.name" :value="item.id" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="年级" prop="gradeId" class="g-item-inline">
						<el-select v-model="form.gradeId" @change="getSubject" placeholder="请选择年级">
							<el-option v-for="(item, index) in gradeData" :label="item.name" :value="item.id" :key="index"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="科目" prop="subjectId" class="g-item-inline">
						<el-select v-model="form.subjectId" placeholder="请选择科目">
							<el-option v-for="(item, index) in subjectData" :label="item.name" :value="item.id" :key="index"></el-option>
						</el-select>
					</el-form-item>
				</template>


				<template v-if="isMulti">
					<el-form-item label="邀请成员" prop="join_user">
						<el-button type="primary" @click="openMemberDialog">选择</el-button>
						<div class="participant-container" v-if="idsChecked.length > 0">
							<p>已选中的参与人</p>
							<template v-for="item of checkedData">
								<div class="tree-top-level" :key="item.app_code" v-if="item.children.length > 0">
									<div class="row">
										<label>{{ item.name }}：</label>
									</div>
									<el-tag size="small" closable v-for="member in item.children" :key="member.id" @close="cancelCheck(member)">{{ member.name }}</el-tag>
								</div>
							</template>
						</div>
						<el-input v-model="form.join_user" style="display:none;"></el-input>
					</el-form-item>
				</template>

				<template v-else>
					<el-form-item label="邀请成员" prop="join_user">
						<el-button type="primary" @click="openMemberDialog">选择</el-button>
					</el-form-item>
					<el-form-item>
						<el-tag v-for="tag in membersNamesData" :key="tag.name" :type="tag.type" closable @close="cancelMemberChecked(tag)">{{ tag.name }}</el-tag>
					</el-form-item>
				</template>


				<el-form-item>
					<el-button type="primary" @click="submitForm('form')">保存</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- 单级 选择成员弹窗 -->
		<el-dialog title="选择成员" :visible.sync="memberVisible" width="800px">
			<el-row>
				<el-col :span="8">
					学段
					<el-select v-model="groupTableData.study_section_id" @change="getOrgpeople" placeholder="请选择学段" size="small">
						<el-option v-for="(item, index) in orgLevel2T" :label="item.name" :value="item.id" :key="index"></el-option>
					</el-select>
				</el-col>
				<el-col :span="8">
					年级
					<el-select v-model="groupTableData.grade_id" @change="getOrgpeople2" placeholder="请选择年级" size="small">
						<el-option v-for="(item, index) in orgLevel3T" :label="item.name" :value="item.id" :key="index"></el-option>
					</el-select>
				</el-col>
				<el-col :span="8">
					<el-input placeholder="搜索教师名字" class="input-with-select" size="small" v-model.trim="groupTableData.n_n_e"
					 @keyup.enter.native="getMembersData" @clear="getMembersData" clearable>
						<el-button slot="append" icon="el-icon-search" @click="getMembersData"></el-button>
					</el-input>
				</el-col>
			</el-row>
			<template>
				<el-table ref="multipleTable" :data="membersData" border tooltip-effect="dark" style="width: 100%" :row-key="getRowKeys"
				:row-class-name="setRowClass" @selection-change="membersChacked">
					<el-table-column type="selection" width="35" align="center" :reserve-selection="true" :selectable="checkSelectable"></el-table-column>
					<el-table-column prop="number" label="登陆账号" width="140" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="name" label="用户名" width="190" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column prop="sub_name" label="科目" width="190" align="center" show-overflow-tooltip></el-table-column>
					<el-table-column label="组织架构" align="center" show-overflow-tooltip>
						<template slot-scope="scope">
							{{ scope.row.org_name == null ? '暂无绑定组织' : scope.row.org_name }}
						</template>
					</el-table-column>
				</el-table>
				<el-pagination background v-if="total_number > groupTableData.size" class="pageing" @size-change="handleSizeChange"
				 @current-change="currentChange" :current-page="groupTableData.page" :page-size="groupTableData.size" layout="total, prev, pager, next, jumper"
				 :total="total_number"></el-pagination>
				<div class="group-add-tableBtns">
					<el-button size="small" @click="memberVisible = false">取消</el-button>
					<!-- <el-button size="small" @click="resetTable()">重置</el-button> -->
					<el-button size="small" type="primary" @click="sureSelect()">确定</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 多级 选择成员弹窗 -->
		<el-dialog title="选择成员" class="multi-dialog" :visible.sync="mulMemberVisible">
			<orgTree ref="organization" titleTxt="成员"></orgTree>
			<span slot="footer" class="dialog-footer">
				<el-button size="small" @click="mulMemberVisible = false">取 消</el-button>
				<el-button size="small" type="primary" @click="checkMember">确 定</el-button>
			</span>
		</el-dialog>

	</div>
</template>

<script>
	import imgUpload from './imgUpload';
	import orgTree from "@/components/common/organization-tree";

	export default {
		name: '',
		components: {
			imgUpload,
			orgTree
		},
		data() {
			return {
				form: {
					picture: '',
					name: '',
					sectionId: '',
					gradeId: '',
					subjectId: '',
					join_user: '',
					create_id: this.$store.getters.userInfo.id
				},
				rules: {
					name: [{
						required: true,
						message: '请输入圈组名称',
						trigger: 'blur'
					}],
					sectionId: [{
						required: true,
						message: '请选择学段',
						trigger: 'change'
					}],
					gradeId: [{
						required: true,
						message: '请选择年级',
						trigger: 'change'
					}],
					subjectId: [{
						required: true,
						message: '请选择科目',
						trigger: 'change'
					}],
					join_user: [{
						required: true,
						message: '请邀请成员',
						trigger: 'change'
					}]
				},
				sectionData: [],
				gradeData: [],
				subjectData: [],
				//单级 选择成员弹窗：
				memberVisible: false,
				orgLevel2T: [{ id: null, name: "全部学段" }],
				orgLevel3T: [{ id: null, name: "全部年级" }],
				groupTableData: {
					study_section_id: null,
					grade_id: null,
					org_id: '',
					n_n_e: '',
					status: 1,
					data_type: 2,
					role_id: 6,
					page: 1,
					size: 7,
					is_diffplat: 1
				},
				membersNamesData: [],
				membersData: [],
				memberSelected: [],
				total_number: 0,
				// 多级 选择成员弹窗
				mulMemberVisible: false,
				checkedData: [],
				idsChecked: [],
			};
		},
		created() {
			this.getSection();
			if (!this.isMulti) { //单级
				this.getOrgLevel2T(); //选择成员：弹窗里面的
			}
		},
		computed: {
			isSchool() {
				return this.$store.getters.isSchool;
			},
			isMulti() {
				return this.$store.getters.isMulti;
			}
		},
		methods: {
			getImgPath(picture) {
				this.form.picture = picture;
			},
			getSection() {
				if (!this.isSchool) return;
				const ajaxUrl = this.isMulti ? 'api/newlevel/platform_org' : 'api/org/org';
				let success = res => {
					this.sectionData = res.data;
					this.gradeData = [];
					this.subjectData = [];
					this.form.sectionId = '';
					this.form.gradeId = '';
					this.form.subjectId = '';
					this.getGrade();
				};
				this.$ajax({
					url: ajaxUrl,
					method: 'get',
					params: {
						level: 2,
						status: 1,
						direction: 'balance',
						data_type: 'arr_all'
					},
					func: {
						success: success
					}
				});
			},
			getGrade() {
				const ajaxUrl = this.isMulti ? 'api/newlevel/platform_org' : 'api/org/org';
				let success = res => {
					this.gradeData = res.data;
					this.subjectData = [];
					this.form.gradeId = '';
					this.form.subjectId = '';
					this.getSubject();
				};
				this.$ajax({
					url: ajaxUrl,
					method: 'get',
					params: {
						level: 3,
						status: 1,
						direction: 'balance',
						data_type: 'arr_all',
						pid: this.form.sectionId
					},
					func: {
						success: success
					}
				});
			},
			getSubject() {
				const ajaxUrl = this.isMulti ? 'api/newlevel/platform_subject' : 'api/cate/subject';
				let success = res => {
					this.subjectData = res.data;
					this.form.subjectId = '';
				};
				this.$ajax({
					url: ajaxUrl,
					method: 'get',
					params: {
						type: 2,
						org_id: this.form.gradeId,
						status: 1
					},
					func: {
						success: success
					}
				});
			},
			openMemberDialog() {
				if (!this.isMulti) { //单级
					this.memberVisible = true;
					this.groupTableData.study_section_id = null
					this.groupTableData.grade_id = null
					this.getMembersData();
					this.getOrgLevel2T();
					this.getOrgLevel3T();
				} else {
					this.mulMemberVisible = true;
					this.$nextTick(() => {
						if (this.checkedData.length > 0) {
							this.$refs.organization.checkIds = this.idsChecked;
							this.$refs.organization.rightData = this.checkedData;
							this.$refs.organization.setChecked(this.idsChecked);
						}
					})
				}

			},
			resetTable(rows) {
				this.groupTableData = {
					study_section_id: null,
					grade_id: null,
					org_id: null,
					n_n_e: '',
					status: 1,
					data_type: 2,
					role_id: 6,
					page: 1,
					size: 7,
					is_diffplat: 1
				};
				this.getMembersData();
				if (rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row);
					});
				} else {
					this.$refs.multipleTable.clearSelection();
					console.log(this.$refs.multipleTable.selection)
				}
			},
			getMembersData() {
				let success = res => {
					this.membersData = res.data.data;
					this.total_number = res.data.data_sum;
				};
				this.$ajax({
					url: '/api/user/user',
					method: 'get',
					params: this.groupTableData,
					func: {
						success: success
					}
				});
			},
			getOrgpeople() {
				this.groupTableData.grade_id = null
				this.groupTableData.org_id = this.groupTableData.study_section_id;
				this.getOrgLevel3T()
				this.getMembersData()
			},
			getOrgpeople2() {
				this.groupTableData.org_id = this.groupTableData.grade_id;
				this.getMembersData()
			},
			getOrgLevel2T() {
				let success = res => {
					let data = res.data;
					if (data && data.length > 0) {
						this.orgLevel2T = data;
					}
					this.orgLevel2T.unshift({ id: null, name: "全部学段" })
				};
				this.$ajax({
					url: 'api/org/org',
					method: 'get',
					params: {
						level: 2,
						status: 1,
						direction: 'balance',
						data_type: 'arr_all'
					},
					func: {
						success: success
					}
				});
			},
			getOrgLevel3T() {
				let success = res => {
					let data = res.data;
					if (data.length === 0) return
					this.orgLevel3T = data;
					this.orgLevel3T.unshift({ id: null, name: "全部年级" })
				};
				this.$ajax({
					url: 'api/org/org',
					method: 'get',
					params: {
						level: 3,
						status: 1,
						direction: 'balance',
						data_type: 'arr_all',
						pid: this.groupTableData.study_section_id
					},
					func: {
						success: success
					}
				});
			},
			// 选中成员弹窗里table，checkbox勾选到的数据:
			membersChacked(val) {
				this.memberSelected = val;
			},
			getRowKeys(row) {
				return row.id;
			},
			checkSelectable(row) {
				let inx = this.membersNamesData.findIndex(item => {
					return item.id == row.id
				})
				return inx === -1;
			},
			setRowClass({ row, rowIndex }) {
				return this.form.join_user.includes(row.id) ? 'custom-row-color' : '';
			},
			//确定选中成员：
			sureSelect() {
				if (this.memberSelected.length == 0) {
					this.$message.warning('请选择成员');
					return;
				}
				//确定选中的成员数据，顺便去重处理：
				let n_arr = this.membersNamesData;
				let s_arr = this.memberSelected;
				n_arr.push.apply(n_arr, s_arr);
				this.membersNamesData = this.FilterByName(n_arr, 'id');
				//邀请的成员Id,字符串格式传去后台：
				this.form.join_user = this.arrChangeString(this.membersNamesData);
				this.memberVisible = false;
			},
			cancelMemberChecked(tag) {
				//把弹窗里table的选中数据对应的选项也删掉
           		this.memberSelected.splice(this.memberSelected.findIndex(x => x.id === tag.id), 1);
				const len = this.$refs.multipleTable.selection.length;
				for (let i = 0; i < len; i++) {
					if (this.$refs.multipleTable.selection[i].id == tag.id) {
						this.$refs.multipleTable.selection.splice(i, 1);
						break;
					}
				}
				//表单里面成员数据删除对应的/
				this.membersNamesData.splice(this.membersNamesData.indexOf(tag), 1);
				//字符串也删对应
				this.form.join_user = this.arrChangeString(this.membersNamesData);
			},

			//json数组data，根据Name字段去重
			FilterByName(data, Name) {
				var map = {},
					dest = [];
				for (var i = 0; i < data.length; i++) {
					var ai = data[i];
					if (i == 0) {
						dest.push(ai);
					} else {
						var filterData = dest.filter(function(e) {
							return e[Name] == ai[Name];
						});
						if (filterData.length == 0) {
							dest.push(ai);
						}
					}
				}
				return dest;
			},
			// 拼字符串
			arrChangeString(arr) {
				let userString = '';
				for (var value of arr) {
					userString += value.id + ',';
				}
				return userString.substring(0, userString.length - 1);
			},
			submitForm(formName) {
				console.log(this.form)
				this.$refs[formName].validate(valid => {
					if (valid) {
						if (!this.uploadOrNot && this.selectFileOrNot) {
							this.$message.warning('请等待封面图片上传完成');
						} else {
							this.saveLive();
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			saveLive() {
				let params = {};
				if (!this.isMulti) { //单级
					params = {
						picture: this.form.picture,
						name: this.form.name,
						study_section_id: this.form.sectionId,
						grade_id: this.form.gradeId,
						subject_id: this.form.subjectId,
						join_user: this.form.join_user,
						create_id: this.form.create_id
					}
				} else { //多级
					params = {
						picture: this.form.picture,
						name: this.form.name,
						study_section_id: this.form.sectionId,
						grade_id: this.form.gradeId,
						subject_id: this.form.subjectId,						
						join_user: this.form.join_user,
						create_id: this.form.create_id,
						status: 1
					}
				}
				let success = data => {
					this.$message.success(data.msg);
					setTimeout(() => {
						this.$router.push({
							path: '/group/manage/selfCreated'
						});
					}, 1000);
				};
				let fail = data => {
					let msg = '';
					if (typeof data.msg == 'object') {
						for (var i = 0; i <= data.msg.length - 1; i++) {
							msg += data.msg[i];
						}
					} else {
						msg = data.msg;
					}
					this.$message.warning(msg);
				};
				this.$ajax.post('/api/group/group_list', params, {
					func: {
						success: success,
						fail: fail
					}
				});
			},
			back() {
				this.$router.back();
			},
			handleSizeChange(val) {
				this.groupTableData.page = 1;
				this.groupTableData.size = val;
				this.getMembersData();
			},
			currentChange(val) {
				this.groupTableData.page = val;
				this.getMembersData();
			},
			/*
			   多级级- 取消--参与人
			*/
			cancelCheck(item) {
				// 删除左侧选中
				this.idsChecked = this.idsChecked.filter(x => {
					return typeof x === 'string' && x.indexOf('_') > -1 ? x.split('_')[0] != item.rel_id : x != item.rel_id;
				});
				//  删除右侧选中
				let length = this.checkedData.length;
				for (let i = 0; i < length; i++) {
					let elem = this.checkedData[i];
					if (elem.app_code === item.user_app_code) {
						elem.children = elem.children.filter(x => x.rel_id != item.rel_id);
					}
				}
				// 删除表单中选择的
				let user = this.form.join_user;
				this.form.join_user = user.split(',').map(Number).filter(x => x != item.rel_id).join(',');
			},
			//多级 - 弹窗选中成员
			checkMember() {
				this.mulMemberVisible = false;
				let check = deep_clone(this.$refs.organization.checkIds);
				this.idsChecked = check;
				this.checkedData = deep_clone(this.$refs.organization.rightData);
				check = check.map(x => {
					return typeof x === 'string' && x.indexOf('_') > -1 ? (x.split('_')[0] + 0) : x;
				})
				check = Array.from(new Set(check));
				this.form.join_user = check.join(',');
			}
		},

	};
</script>
<style lang='scss'>
	.group-add{
		.group-add-cont {
			.group-name {
				width: 450px;
			}
		}

		.participant-container {
			background-color: #EEF4F9;
			padding: 20px;

			p {
				border-bottom: 1px solid #D5DEE5;
			}

			.tree-top-level {
				padding-bottom: 20px;

				.row {
					height: 25px;
					line-height: 25px;
					padding-top: 10px;
					font-size: 16px;
					color: black;
				}

				.el-tag {
					background-color: #fff;
					border-color: #fff;
					color: black;
					margin: 5px 10px 5px 0;
				}

				.el-tag__close {
					color: black;
				}
			}
		}
		.custom-row-color{
			background-color: #f0f9eb;
		}
	}
</style>
